package com.dcs.cn.item.service.impl;

import cn.com.dcsgo.exception.BizIllegalException;
import cn.com.dcsgo.utils.BeanUtils;
import cn.com.dcsgo.api.dto.ItemDTO;
import cn.com.dcsgo.api.dto.OrderDetailDTO;
import com.dcs.cn.item.domain.po.Item;
import com.dcs.cn.item.enums.ItemStatus;
import com.dcs.cn.item.mapper.ItemMapper;
import com.dcs.cn.item.service.IItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author xzq
 * @since 2025-03-09
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Override
    public void deductStock(List<OrderDetailDTO> items) {
        //预处理
        String sqlStatement = "com.dcs.cn.item.mapper.ItemMapper.updateDeductStock";
        boolean r = false;
        try{
            r = executeBatch(items,(sqlSession,entity) -> {
                sqlSession.update(sqlStatement,entity);
            });
        }
        catch (Exception e){
            log.error("批量扣减库存失败",e);
            throw new BizIllegalException("变更库存异常,可能是库存不足!",e);
        }
        if(!r){
            throw new BizIllegalException("扣减库存失败,可能是库存不足!");
        }
    }

    @Override
    public void addStock(List<OrderDetailDTO> items) {
        //预处理
        String sqlStatement = "com.dcs.cn.item.mapper.ItemMapper.updateAddStock";
        boolean r = false;
        try{
            r = executeBatch(items,(sqlSession,entity) -> {
                sqlSession.update(sqlStatement,entity);
            });
        }
        catch (Exception e){
            log.error("批量添加库存失败",e);
            throw new BizIllegalException("添加库存异常",e);
        }
        if(!r){
            throw new BizIllegalException("添加库存失败!");
        }
    }

    @Override
    public List<ItemDTO> queryItemByIds(List<Long> ids) {
        List<Item> items = lambdaQuery()
                .in(Item::getId, ids)
                .eq(Item::getStatus, ItemStatus.NORMAL.getCode())
                .list();
        return BeanUtils.copyList(items, ItemDTO.class);
    }
}
